
<template>
    <view class="main">
        <swiper class="swiper">
            <swiper-item>
                <view class="equipment-infos">
                    <view class="equipment-info">
                        <view class="title">基础信息</view>
                        <view class="info">
                            <view class="content">
                                <text class="text">
                                    设备名称：{{ deviceInfo.name }}
                                </text>
                            </view>
                            <view class="content">
                                <view class="text">
                                    设备编号：{{ deviceInfo.id || "暂无" }}
                                </view>
                            </view>
                            <view class="content">
                                <text class="text"> 
                                    上线时间：{{ deviceInfo.create_time || "暂无" }}
                                </text>
                            </view>
                            <view class="content">
                                <text class="text">
                                    网关编号：{{ deviceInfo.code || "暂无" }}
                                </text>
                            </view>
                            <view class="content">
                                <text class="text">{{ statusText }}</text>
                            </view>
                        </view>
                    </view>
                </view>
            </swiper-item>
        </swiper>
    </view>
</template>

<script>
import detailModule from "@/common/mixins/detail-module";
/* 设备数字档案 */
import {
  getEquipmentTypeOptions,
  putEquipmentEquipmentType,
  deleteEquipmentEquipmentType,
} from "@/common/api/equipment-type.js";
/* 服务申请记录 */
import { getServiceOrderRecords2 } from "@/common/api/service-order-record.js";
/* 维护记录 */
import { getMaintenanceRecords2 } from "@/common/api/maintenance-record.js";
import Upload from "@/components/public/upload";
import dictType from "@/components/public/dictType";
import uniPopup from "@/components/uni-popup/uni-popup";
import popupLoading from "@/components/public/loading/popup";
import { mapState } from "vuex";
import { delayFunc } from "@/common/util";
import serviceLog from "@/components/public/item/serviceLog";
import Tab from "@/components/public/tabs/service";
import Router from "@/common/js/router";
import { setTime } from "@/utils";
import {
  getEquipment,
  editMaintrinUser,
  editAttachFile,
} from "@/common/api/equipment.js";

import {
  imgBaseUrl,
  uploadUrl,
  imgBaseUrlV0,
  imgBaseUrlV1,
  imgBaseUrlV2,
} from "@/common/config/index";
import { getCompanyUserList } from "@/common/api/user";
export default {
  props:{
	deviceInfo:{
	  type: [Object],
	  default: null,
	},
    equipmentId:{
	  type: Number,
	  default: null
	},
	Boxid:{
		type:[Number,String],
		default:null
	}
  },
  mixins: [detailModule],
  components: {
    Upload,
    dictType,
    uniPopup,
    popupLoading,
    serviceLog,
    Tab,
  },
  computed: {
    ...mapState("User", ["token"]),
    statusText() {
        const statusMap = {
          1: '正常',
          2: '故障',
          3: '离线'
        }
        return `设备状态：${statusMap[this.deviceInfo.status] || '未知状态'}`;
      }
  },
  data() {
    return {
      imgBaseUrl,
      imgBaseUrlV0,
      imgBaseUrlV1,
      qrcodeURL: "",
      qrcodeSacnURL: "",
      imgList: [],
      userList: [],
      currentTab: 0,
      tabs: [
        {
          name: "设备档案",
        },
        {
          name: "服务申请记录",
        },
        {
          name: "维护记录",
        },
      ],
      equipment: null,

      /* 设备档案 */
      // 分类
      equipmentTypeSelectShow: false,
      equipmentTypeOptions: [],
      isEditEquipmentType: false,
      currentEquipmentTypeName: "",
      deleteTypeViewShow: false,
      showEquipmentTypeEdit: false,
      // 其他
      showContact: false,
      /* 服务申请记录 */
      serviceTypeOptions: [],
      serviceOrderRecords: [],

      /* 维护记录 */
      maintenanceRecords: [],
      isLoading: true,
      listQuery: {
        search: null,
        page: 1,
        limit: 20,
        sort: {
          id: "",
        },
        device_id: null,
      },
	  SensorList:[],
      mixinViewOptions: {
        getURL: "/device/detail",
        isPage: false,
        isShowLoading: false,
        reachBottom: false,
        createdIsNeed: false,
        pullDown: false,
      },
    };
  },
  created() {
	// this.listQuery.gear_box_id = this.dataForm.gear_box_id = this.Boxid
	// this.listQuery.device_id = this.dataForm.deviceId = this.equipmentId;
	// console.log("this.equipmentId",this.dataForm.id)
  },
  mounted(){
	// this.init();
	  
	// this.$nextTick(async () => {
	//   // this.openLoading();
	//   this.initData();
	// });
  },
  // async onLoad(e) {
  //   if (!e.equipmentId) return;
   
  // },
  // async onPullDownRefresh() {
  //   uni.showLoading({
  //     title: "加载中",
  //   });
  //   await this.initData();
  //   uni.stopPullDownRefresh();
  //   uni.hideLoading();
  // },
  // async onReachBottom() {
  //   if (this.currentTab === 2) {
  //     this.listQuery.page++;
  //     uni.showLoading({
  //       title: "加载中",
  //       mask: true,
  //     });
  //     await this.getMaintenanceRecords();
  //   }
  // },
  methods: {
    fetchComplete(err, data = {}) {
      console.log(data, "??fetchComplete");
      data.user = (data.user || []).map((i) => {
        return {
          ...i,
          label: [i.name, i.mobile].join("/"),
          value: i.id,
        };
      });
	  this.SensorList = data.Sensors.map(item => {
		  return {
			  ...item,   
			  time:this.$moment(data.service_end_time).format("YYYY-MM-DD")
		  }
	  })
      data.attachment = data.attachment || [];
      if (data.service_end_time) {
        data.service_end_time = this.$moment(data.service_end_time).format(
          "YYYY-MM-DD"
        );
      }
      if (data.company) {
        data.keyContact = [
          data.company.main_contact_name,
          data.company.contact_mobile,
        ].join("/");
      }
    },
    init() {
      this.qrcodeSacnURL = imgBaseUrlV2 + "qrcode.png";
      this.qrcodeURL = imgBaseUrlV1 + "exp_qrcode.jpg";
    },
    async initData() {
      let time = +new Date();
	  this.dataForm.deviceId = this.equipmentId
      await this.getDataInfo();
      await Promise.all([
        this.getEquipmentTypeOptions(),
        this.getCompanyUserList(),
        this.getServiceOrderRecords(),
        this.getMaintenanceRecords(),
      ])
        .then((res) => {})
        .catch((err) => {
          console.log("err", err);
        });
      let now = +new Date();

      if (now - time < 500) {
        await delayFunc(now - time);
      }
      this.isLoading = false;
      this.closeLoading();
    },
    onChangeTab(tab, index) {
      this.currentTab = index;
    },
	/* 获取设备信息 */
	getDeviceInfo() {
	  this.$http
	},
    getCompanyUserList() {
      return getCompanyUserList({})
        .then((res) => {
          let data = res.data || [];
          data.forEach((i) => {
            i.checked = false;
            i.label = [i.name || "", i.mobile || ""].join("/");
            i.value = i.id;
          });
          this.userList = data;
          // console.log(this.userList, "?? this.userList");
        })
        .catch((err) => {});
    },
    /* 设备数字档案 */
    getEquipmentTypeOptions() {
      return getEquipmentTypeOptions().then((response) => {
        this.equipmentTypeOptions = response;
      });
    },
    uploadSuccess(ret) {
		console.log(ret,"飞飞飞")
		this.initData()
	},
    deleteEquipmentType(equipmentType) {
      if (this.isEditEquipmentType) {
        this.currentEquipmentTypeName = equipmentType;
        this.deleteTypeViewShow = true;
      }
    },

    getServiceOrderRecords() {
      return getServiceOrderRecords2({ device_id: this.dataForm.deviceId }).then(
        (res) => {
          let data = res.data || {};
          let { list = [] } = data;
          let o = {
            2: "https://rhws.oss-cn-chengdu.aliyuncs.com/icon_v1/yiwancheng.png",
            3: "https://rhws.oss-cn-chengdu.aliyuncs.com/icon_v1/yiguanbi.png",
            0: "https://rhws.oss-cn-chengdu.aliyuncs.com/icon_v1/daigoutong.png",
            1: "https://rhws.oss-cn-chengdu.aliyuncs.com/icon_v1/jinxingzhong.png",
          };
          list.forEach((i) => {
            i.statusIcon = o[i.status] || o[0];

            i.title =
              (this.dataInfo.device_name || "") + "申请的" + i.service_content;
          });
		  console.log(list,"list??")
          this.serviceOrderRecords = list;
        }
      );
    },
    openServiceRecordDetail(item, index) {
      Router.push({
        path: "/pages/service-order-detail/service-order-detail",
        query: {
          id: item.id,
          name: encodeURIComponent(item.device_name),
        },
      });
    },
    /* 维护记录 */
    getMaintenanceRecords() {
      return getMaintenanceRecords2(this.listQuery)
        .then((res) => {
          let page = this.listQuery.page || 1;
          let data = res.data || {};
          uni.hideLoading();
          const { list = [], total = 0 } = data;
          if (page <= 1) {
            this.maintenanceRecords.length = 0;
          }

          list.forEach((e) => {
            e.fold = true;
          });
          this.maintenanceRecords.push(...list);
          if (list.length == 0) {
            this.listQuery.page--;
            if (this.listQuery.page > 1) {
              return this.message.error("已无更多");
            }
          }
        })
        .catch(() => {
          uni.hideLoading();
        });
    },

    toggleFold(e) {
      e.fold = !e.fold;
      this.$forceUpdate();
    },
    openService() {
      uni.$emit("change-page", 1);
      console.log(
        this.dataInfo.servicer,
        "?this.dataInfo.service",
        this.dataInfo
      );
      Router.push({
        path: "/pages/service-provider-detail/service-provider-detail",
        query: {
          ...this.dataInfo.servicer,
        },
      });
    },
    onChangeSwiper(e) {
      let index = e.detail.current;
      this.currentTab = index;
    },
    onEdidUser() {
      this.userList.forEach((i) => {
        i.checked = (this.dataInfo.maintainUser.id == i.id);
      });
      this.$refs.popup.open();
    },
    onUpload() {
      uni.chooseImage({
        count: 9,
        success: (chooseImageRes) => {
          const tempFilePaths = chooseImageRes.tempFilePaths;
          let len = tempFilePaths.length;
          let load = 0;
          console.log(uploadUrl, "?uploadUrl", tempFilePaths);
          if (len) {
            uni.showLoading({
              title: "上传中",
            });
          }
          tempFilePaths.forEach((i) => {
            uni.uploadFile({
              url: uploadUrl, //仅为示例，非真实的接口地址
              filePath: i,
              name: "file",
              header: {
                authorization: "Bearer " + this.token,
              },
              formData: {
                // user: "test",
              },
              success: (uploadFileRes) => {
                let res = uploadFileRes.data;
                try {
                  res = JSON.parse(res);
                } catch (err) {
                  return this.message.error("上传图片失败,请重试");
                }
                let data = res.data;
                if (res.code !== this.$ERR_OK) {
                  return this.message.error(res.message || "上传图片失败");
                }
                let path = data.path;
				this.$nextTick( _ => {
					this.initData()
				})
                this.dataInfo.attachment.push(path);
                editAttachFile({
                  device_id: this.dataInfo.id,
                  img: this.dataInfo.attachment,
                });
              },
			  
              complete: (r) => {
                load += 1;
                if (len == load) {
                  uni.hideLoading();
                }
              },
            });
          });
        },
      });
    },
    onDeleteImg(index) {
      let arr = this.dataInfo.attachment.slice(0);
      arr.splice(index, 1);
      uni.showLoading({
        title: "删除中",
      });
      editAttachFile({
        device_id: this.dataInfo.id,
        img: arr,
      })
        .then((res) => {
          uni.hideLoading();
          this.dataInfo.attachment.splice(index, 1);
        })
        .catch((err) => {
          uni.hideLoading();
        });
    },
    onCheckedUser(item, index) {
      item.checked = !item.checked;
      this.userList.splice(index, 1, item);
    },
    onConfirmUser() {
		this.dataForm.deviceId = this.equipmentId
      let list = this.userList.filter((i) => i.checked);
	  // console.log(this.userList,'this.userList')
      let ids = list.map((i) => i.id);
      uni.showLoading({
        title: "加载中",
      });
      editMaintrinUser({
        device_id: this.dataInfo.id,
        user_id: ids.join(","),
      })
        .then((res) => {
          uni.hideLoading();
          if (res.code !== this.$ERR_OK) {
            return this.message.error(res.message || "操作失败,请重试");
          }
          this.dataInfo.maintainUser = list.map((i) => {
            return {
              ...i,
              name: i.name,
            };
          });
        })
        .catch((err) => {
          uni.hideLoading();
        });
      this.close();
    },
    onCancelUser() {
      this.close();
    },
    closeLoading() {
      this.$refs.popupLoading && this.$refs.popupLoading.close();
    },
    // openLoading() {
    //   this.$refs.popupLoading && this.$refs.popupLoading.open();
    // },
    open() {
      this.$refs.popup && this.$refs.popup.open();
    },
    close() {
      this.$refs.popup && this.$refs.popup.close();
    },
    open() {
      this.$refs.popup && this.$refs.popup.open();
    },
    onClickShowQrcode() {
	  console.log(this.dataForm,'this.dataForm')
      Router.push({
        path: "/pageA/equipment/qrcode/index",
        query: {
          ...this.dataForm,
          equipmentId: this.equipmentId,
        },
      });
    },
    createQrcode(url) {
      console.log(url, "??");
    },
  },
};
</script>

<style lang="stylus" scoped>
@import '~@/common/stylus/variable';

.main, page {
  min-height: calc(100vh - var(--window-top));
  position: relative;
}

/* 设备数字档案 */
.equipment-infos {
  padding: 30rpx;
  box-sizing: border-box;

  .equipment-info {
    background-color: #1A3156;
    margin-bottom: 20rpx;
    border-radius: 8rpx;

    .title {
      position: relative;
      line-height: 80rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
      color: #fff;

      .operation {
        float: right;
        color: color-active;
        font-size: 28rpx;
      }

      &::after {
        content: '';
        position: absolute;
        left: 0;
        top: 20rpx;
        width: 2px;
        height: 40rpx;
        background-color: color-active;
      }
    }
  }

  .info {
    padding: 0 30rpx 10rpx;
    font-size: 28rpx;
    color: #fff;
	>.list {
		padding:10rpx 15rpx;
		background: #26406A;
		border-radius: 5px;
		margin-bottom: 15rpx;
	}
    > .content {
      padding-bottom: 20rpx;
      display: flex;
      flex-direction: row;

      .text {
        flex: 1;

        .service-provider {
          border-bottom: 3rpx solid color-active;
          color: color-active;
        }
      }

      .qrcode {
        color: color-active;
      }

      .equipment-type-right-icon {
        width: 32rpx;
      }

      .equipment-type-view {
        display: inline;

        .equipment-type {
          display: inline;

          .equipment-type-text {
            &.delete-operation {
              border: 3rpx solid #f66;
              border-radius: 10rpx;
              padding: 0 5rpx;

              .delete {
                color: #f66;
                padding-left: 6rpx;
              }
            }
          }
        }
      }

      .contact-right-icon {
        width: 40rpx;
      }
    }
  }
}

.qrcode-view {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  background-color: rgba(0, 0, 0, 0.5);
  text-align: center;

  .qrcode {
    width: 450rpx;
    border-radius: 5rpx;
    margin-top: 250rpx;
  }

  .close-icon {
    width: 70rpx;
    height: 70rpx;
    margin-top: 50rpx;
  }
}

/* 服务申请记录 */
.service-records {
  position: relative;
  padding: 30rpx;

  >.item {
    margin-top: 20rpx;

    &:first-child {
      margin-top: 0;
    }
  }
}

/* 维护记录 */
.maintenance-view {
  padding: 30rpx;
}

.maintenance-record-group {
  background-color: #1A3156;
  padding: 25rpx 30rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;

  &:last-child {
    margin-bottom: 0;
  }

  .info {
    display: flex;
	text {
		color:#fff;
	}
    >.bd {
      flex: 1;
      font-size: 30rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: color-white;
    }

    .status-normal, .status-error {
      position: relative;
      display: flex;
      font-size: 24rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 600;
      padding: 0 12rpx;
      border-radius: 20rpx;
      line-height: 40rpx;
      align-items: center;
    }

    .circle {
      position: relative;
      width: 12rpx;
      height: 12rpx;
      border-radius: 12rpx;
      margin-right: 10rpx;
    }

    .status-normal {
      color: color-success;

      >.circle {
        background: color-success;
      }
    }

    .status-error {
      color: color-danger;

      >.circle {
        background: color-danger;
      }
    }
  }
}

.swiper {
  position: relative;
  height: calc(100vh - 82rpx - var(--window-top));
  overflow: auto;

  swiper-item {
    overflow: auto;
  }
}

.upload {
  padding: 0 20rpx;
}

.qrcodeURL {
  width: 30rpx;
  height: 30rpx;
  margin-left: 6rpx;
  margin-top: -4rpx;
  vertical-align: middle;
}
</style>